//
//  AIGirlWelcomeViewController.swift
//  AIGirl
//
//  Created by Rae on 2024/1/16.
//

import UIKit
import AVKit
import AuthenticationServices

class AIGirlWelcomeViewController: AIGirlBaseViewController {

    private lazy var appleButton = c_make_ex(UIButton.self)
        .image("AIGirl_Signin_apple").end()
    private lazy var guestButton = c_make_ex(UIButton.self)
        .image("AIGirl_Signin_guest").end()
    private lazy var termsLabel = c_make_ex(UnderlinedLabel.self)
        .text("Terms of Use").color("#F2F2FD").alignment(.right).end()
    private lazy var privacyLabel = c_make_ex(UnderlinedLabel.self)
        .text("Privacy Policy").color("#F2F2FD").end()
    private var player: AVPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = .black
        guard let path = Bundle.main.path(forResource: "launchVideo", ofType: "mov") else {
            return
        }
        let playerItem = AVPlayerItem(url: URL(fileURLWithPath: path))
        player = AVPlayer(playerItem: playerItem)
        let layer = AVPlayerLayer(player: player)
        layer.videoGravity = .resizeAspectFill
        layer.frame = UIScreen.main.bounds
        view.layer.addSublayer(layer)
        player?.volume = 0
        player?.play()
        
        view.subviews{
            appleButton
            guestButton
            termsLabel
            privacyLabel
        }
        
        appleButton.leading(30).bottom(.safe_bottom + 92).size(50)
        guestButton.trailing(30).height(50)
        guestButton.Leading == appleButton.Trailing + 15
        guestButton.CenterY == appleButton.CenterY
        termsLabel.trailing(.screenWidth/2 + 7.5).bottom(.safe_bottom + 40)
        privacyLabel.leading(.screenWidth/2 + 7.5).bottom(.safe_bottom + 40)
        
        let termTap = UITapGestureRecognizer(target: self, action: #selector(clickTermLabel))
        let privacyTap = UITapGestureRecognizer(target: self, action: #selector(clickPrivacyLabel))
        termsLabel.isUserInteractionEnabled = true
        privacyLabel.isUserInteractionEnabled = true
        termsLabel.addGestureRecognizer(termTap)
        privacyLabel.addGestureRecognizer(privacyTap)
        appleButton.addTarget(self, action: #selector(clickAppleButton), for: .touchUpInside)
        guestButton.addTarget(self, action: #selector(clickGuestButton), for: .touchUpInside)
        // 监听播放结束通知
        NotificationCenter.default.addObserver(self,
                                  selector: #selector(playerDidFinishPlaying),
                                  name: .AVPlayerItemDidPlayToEndTime,
                                 object: playerItem)
    }
    
    @objc func playerDidFinishPlaying() {
        // 重置播放头到起始位置
        player?.seek(to: .zero)
        // 开始播放
        player?.play()
    }
    
    @objc private func clickAppleButton(){
        
        ToastTool.show()
        AppleLoginTool.instence.show {[weak self] user, token in
            self?.request.start(.ThirdLogin(user: user, userStr: token), type: AIGirlUserModel.self, completion: { result in
                if result.isSuccessful, let model = result.model {
                    GlobalTool.userModel = model
                    UserDefaultsManager.setString(model.sendCoins, forKey: .sendCoin)
                    if model.gender != 0 {
                        UIApplication.window?.rootViewController = AIGirlTabBarViewController()
                    }else{
                        self?.navigationController?.pushViewController(AIGirlUserInfoNameViewController(), animated: true)
                    }
                }
            })
        } failure: { error in
            ToastTool.dismiss()
            error.errorDescripton.toast_error
        }
    }
    @objc private func clickGuestButton(){
        request.start(.TouristLogin,type: AIGirlUserModel.self) { result in
            if result.isSuccessful, let model = result.model {
//                print(model)
                GlobalTool.userModel = model
                UserDefaultsManager.setString(model.sendCoins, forKey: .sendCoin)
                if model.gender != 0 {
                    UIApplication.window?.rootViewController = AIGirlTabBarViewController()
                }else{
                    UserDefaultsManager.setInt(1, forKey: .currentPage)
                    self.navigationController?.pushViewController(AIGirlUserInfoNameViewController(), animated: true)
                }
            }            
        }
    }
    @objc private func clickTermLabel(_ gesture: UITapGestureRecognizer){
        guard let view = gesture.view as? UILabel else { return }
        let webVc = AIGirlWebViewController()
        webVc.urlString = AGirlConstants.terms
        webVc.titleName = view.text
        self.navigationController?.pushViewController(webVc, animated: true)
    }
    @objc private func clickPrivacyLabel(_ gesture: UITapGestureRecognizer){
        guard let view = gesture.view as? UILabel else { return }
        let webVc = AIGirlWebViewController()
        webVc.urlString = AGirlConstants.policy
        webVc.titleName = view.text
        self.navigationController?.pushViewController(webVc, animated: true)
    }
}

class UnderlinedLabel: UILabel {
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSRange(location: 0, length: text.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: textRange)
            self.attributedText = attributedText
        }
    }
}

public enum ResonseError {
    
    /// http请求报错
    case httpError(_ code: Int, _ description: String)
    
    /// 后端请求报错
    case customError(_ code: Int, _ description: String)
    
    /// 前端处理报错
    case clientError(_ code: Int, _ description: String)
    
    /// 错误码
    public var errorCode: Int {
        switch self {
        case .httpError(let code,_):
            return code
        case .customError(let code,_):
            return code
        case .clientError(let code,_):
            return code
        }
    }
    
    /// 错误描述
    public var errorDescripton: String {
        switch self {
        case .httpError(_, let description):
            return description
        case .customError(_, let description):
            return description
        case .clientError(_, let description):
            return description
        }
    }
    
}

public struct ResponseErrorInfo {
    
    /// 错误码
    public let errorCode: Int
    
    /// 错误信息描述
    public let errorDescripton: String
    
    /// 当前请求信息
    public let request: URLRequest?
    
    public init(_ error: ResonseError, _ request: URLRequest?) {
        self.errorCode = error.errorCode
        self.errorDescripton = error.errorDescripton
        self.request = request
    }

}

typealias AppleLoginToolSuccessClosures = (_ user: String, _ token: String) -> Void
typealias AppleLoginToolFailureClosures = (_ error: ResponseErrorInfo) -> Void

class AppleLoginTool: NSObject {
    
    static let instence = AppleLoginTool()
    
    private override init() {
        
    }
    
    override func copy() -> Any {
        return AppleLoginTool.instence // self
    }
    
    override func mutableCopy() -> Any {
        return AppleLoginTool.instence // self
    }
    
    private weak var parentController: UIViewController?
        
    private var successCompelecte: AppleLoginToolSuccessClosures?
    private var failureCompelecte: AppleLoginToolFailureClosures?
    
    public func isPast() -> Void {
        let provider = ASAuthorizationAppleIDProvider.init()
        provider.getCredentialState(forUserID: "") { (status, error) in
            switch status {
            case .revoked: do { // 已撤销
                
                }
            case .authorized: do {  // 已授权
                
                }
            case .notFound: do {    // 未发现
                
                }
            case .transferred: do { // 已转移
                
                }
            @unknown default:
                break
            }
        }
    }
    
    public func show(success: AppleLoginToolSuccessClosures? = nil, failure: AppleLoginToolFailureClosures? = nil) {
        successCompelecte = success
        failureCompelecte = failure
        let provider = ASAuthorizationAppleIDProvider.init()
        let request = provider.createRequest()
        let controller = ASAuthorizationController.init(authorizationRequests: [request])
        controller.delegate = self
        controller.presentationContextProvider = self
        controller.performRequests()
    }
    
}


@available(iOS 13, *)
extension AppleLoginTool: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return UIApplication.window ?? UIWindow()
    }
}

@available(iOS 13, *)
extension AppleLoginTool: ASAuthorizationControllerDelegate {
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        var baseError: ResponseErrorInfo?
        switch error._code {
        case ASAuthorizationError.Code.canceled.rawValue:
            baseError = ResponseErrorInfo(.customError(0, "Cancel authorization!"), nil)
        case ASAuthorizationError.Code.failed.rawValue:
            baseError = ResponseErrorInfo(.customError(0, "Authorization request failed!"), nil)
        case ASAuthorizationError.Code.invalidResponse.rawValue:
            baseError = ResponseErrorInfo(.customError(0, "Invalid authorization request response!"), nil)
        case ASAuthorizationError.Code.notHandled.rawValue:
            baseError = ResponseErrorInfo(.customError(0, "Failed to process authorization request!"), nil)
        default:
            baseError = ResponseErrorInfo(.customError(0, "Privilege grant failed!"), nil)
        }
        guard let error = baseError, let closure = failureCompelecte else { return }
        closure(error)
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if authorization.credential is ASAuthorizationAppleIDCredential {
            let credential = authorization.credential as! ASAuthorizationAppleIDCredential
            let user = credential.user
            guard let identityToken = credential.identityToken else {
                let baseError = ResponseErrorInfo(.customError(0, "identityToken is NULL"), nil)
                guard let closure = failureCompelecte else { return }
                closure(baseError)
                return
            }
            guard let token = String.init(data: identityToken, encoding: .utf8) else {
                let baseError = ResponseErrorInfo(.customError(0, "identityToken is NULL"), nil)
                guard let closure = failureCompelecte else { return }
                closure(baseError)
                return
            }
            guard let closure = successCompelecte else { return }
            closure(user, token)
        } else if authorization.credential is ASPasswordCredential {
            let baseError = ResponseErrorInfo(.customError(0, "Privilege grant failed!"), nil)
            guard let closure = failureCompelecte else { return }
            closure(baseError)
        } else {
            let baseError = ResponseErrorInfo(.customError(0, "Privilege grant failed!"), nil)
            guard let closure = failureCompelecte else { return }
            closure(baseError)
        }
    }
}
